<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ include file="/jsp/common/common.jsp"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
        <link rel="stylesheet" type="text/css" href="<c:url value="/static/jquery-easyui/themes/default/easyui.css"/>">
        <link rel="stylesheet" type="text/css"
            href="<c:url value="/static/jquery-easyui/themes/icon.css"/>">
        <script type="text/javascript"
            src="<c:url value="/static/jquery-easyui/jquery-1.6.min.js"/>"></script>
        <script type="text/javascript"
            src="<c:url value="/static/jquery-easyui/jquery.easyui.min.js"/>"></script>
        <script type="text/javascript"
            src="<c:url value="/static/jquery-easyui/plugins/jquery.panel.js"/>"></script>
        <script type="text/javascript"
            src="<c:url value="/static/jquery-easyui/plugins/jquery.datagrid.js"/>"></script>
        <script type="text/javascript"
            src="<c:url value="/static/jquery-easyui/plugins/jquery.messager.js"/>"></script>
        <script type="text/javascript"
            src="<c:url value="/static/jquery-easyui/ext-for-framework.js.jsp"/>"></script>
        <script type="text/javascript" src="<c:url value="/static/jquery-easyui/locale/easyui-lang-zh_CN.js"/>"></script>   
        <script type="text/javascript"
            src="<c:url value="/static/js/common.js"/>"></script>           
        <script>
		var map = {}; // 数量
        var selectMap = {};//材料是否被选择map
			function initList(listDisplayEId) {
				$('#' + listDisplayEId).datagrid(
						{
							url : "<c:url value='/mater/findSelectMaterForUnusualSelf.do?materId='/>"+ document.getElementsByName("ordMaterId")[0].value,
							nowrap : false,
							striped : true,
							collapsible : true,
							remoteSort : true,
							notSelectByRow : false,
							toolbar : [
									{
										id : listDisplayEId + '_btn_edit',
										text : '提交',
										iconCls : 'icon-edit',
										handler : function() {	
											var rows = $('#listDisplay2').datagrid('getRows');	
											for(var i=0; i<rows.length; i++){
											    var rowIndex=$('#listDisplay2').datagrid('getRowIndex',rows[i]['mid']);
												$('#listDisplay2').datagrid('endEdit', rowIndex);
											}

											var row = $('#listDisplay2').datagrid('getRows');	
											if(row.length == 0){
												$.messager.alert('提示','请选择一条记录操作！','info');
												return;
											}else{
												var userList = new Array(); 
												var jsonFater;
												for (var i = 0 ; i < row.length;i++){
													
													if ( row[i]['materNum'] == "" || !isNumberAndNoZero(row[i]['materNum'])  ){
														$.messager.alert("提示", "材料"+row[i]['materName']+"，（重量/个/份 ）请填写数字！", 'info');
														return false;
													}
													if ( row[i]['materValueUndressed'] == "" || !isNumberAndNoZero(row[i]['materValueUndressed'])  ){
                                                        $.messager.alert("提示", "材料"+row[i]['materName']+"的（总价格 ）请填写数字！", 'info');
                                                        return false;
                                                    }
													var  jsonSun = "{materId:'"+row[i]['materId']+"',supId:'"+row[i]['supId']+"',materNum:'"+row[i]['materNum']+"',materLevel:'"+row[i]['materLevel']+"'}";
													userList.push(jsonSun);
												}
												jsonFater = JSON.stringify(userList);
												var str = "json="+jsonFater;	
												document.getElementsByName("materdategridList")[0].value = jsonFater;
												$.messager.confirm('提示', '是否提交记录？', function(r){
													//方法函数 进入后台
													if(r){
														addMater();
													}
												});
											}
										}
									}
									],
							onLoadError:function(){
								$.messager.alert('错误','获取数据失败，请与管理员联系！','error');
							},
							onLoadSuccess:function(){ 
								//初始化 复选框
				                var allrows = $('#listDisplay').datagrid("getRows");
				                for (var i = 0; i < allrows.length; i++) {
				                    var rowIndex = $('#listDisplay').datagrid('getRowIndex', allrows[i]['mid']);
				                    var hasSelect = allrows[i]['mid'] in selectMap;
				                    if(hasSelect){
		                               //$('#listDisplay').datagrid("checkRow",rowIndex);
				                    } else {
			                            var allRowsChecked = $("#listDisplay").datagrid('getChecked');
			                            for (var j = 0; j < allRowsChecked.length; j++) {
			                                if( allrows[i]['mid']==allRowsChecked[j]['mid']){
			                                	$('#listDisplay').datagrid("uncheckRow",rowIndex);
			                                }
			                            }
				                    }
				                } 
								//初始化数量 和 价格
								var rows = $('#'+listDisplayEId).datagrid('getRows');	
								if(rows.length > 0){
									for (var i = 0 ; i < rows.length;i++){
										//数量
										var key = rows[i]['mid'];
										var has = key in map; 
										if(has){
											rows[i]['materNum'] = map[key];
											$('#listDisplay').datagrid('refreshRow', i);
										}
									}
								}
							
				            	$(".datagrid-row").mouseover(function(e){  
				            		if(checkHover(e,this)){
				            			var foodId = $(this).find('td').eq(1).text();
					        			var index = $('#listDisplay').datagrid('getRowIndex', foodId);
						        		$('#listDisplay').datagrid('beginEdit',index);
					                }
				                }); 
				        		$(".datagrid-row").mouseout(function(e){  
				        			if(checkHover(e,this)){
				        				var foodId2 = $(this).find('td').eq(1).text();
				        				var index2 = $('#listDisplay').datagrid('getRowIndex', foodId2);
				        				$('#listDisplay').datagrid('endEdit',index2);
				        				
				        				//数量
				        				if( $(this).find('td').eq(14).text()!=''){
					        				map[$(this).find('td').eq(1).text()] = $(this).find('td').eq(14).text(); 
					        				//已选材料设置------start
	                                        var table2Index = $('#listDisplay2').datagrid('getRowIndex',$(this).find('td').eq(1).text());
	                                        if(table2Index != -1){
	                                            var rowDateTable2 = $('#listDisplay2').datagrid('getRows', table2Index);
	                                            for (var m = 0 ; m < rowDateTable2.length;m++){
	                                            	if(rowDateTable2[m]['mid']==$(this).find('td').eq(1).text()){
	                                            	   rowDateTable2[m]['materNum']=$(this).find('td').eq(14).text();
	                                                   $('#listDisplay2').datagrid('refreshRow', table2Index);
	                                            	}
	                                            }
	                                        }
	                                        //已选材料设置------end
				        				}else{
				        					//已选材料设置------start
                                            var table2Index = $('#listDisplay2').datagrid('getRowIndex',$(this).find('td').eq(1).text());
                                            if(table2Index != -1){
                                                var rowDateTable2 = $('#listDisplay2').datagrid('getRows', table2Index);
                                                for (var m = 0 ; m < rowDateTable2.length;m++){
                                                    if(rowDateTable2[m]['mid']==$(this).find('td').eq(1).text()){
                                                       rowDateTable2[m]['materNum']="";
                                                       $('#listDisplay2').datagrid('refreshRow', table2Index);
                                                    }
                                                }
                                            }
                                            //已选材料设置------end
				        					delete map[$(this).find('td').eq(1).text()];
				        				}
				        				
				        			}
				        		});
				        	} 
							,onClickRow:function(rowIndex){
								$(".myrad").prop("checked",false);
								$(".myrad").eq(rowIndex).prop("checked",true);
								$('#listDisplay').datagrid('beginEdit', rowIndex);
							}
							,onCheck:function(rowIndex,rowData){
				                selectMap[rowData['mid']]=1;
								$('#listDisplay2').datagrid('appendRow',{
									mid:rowData['mid'],
									materId:rowData['materId'],
									materName:rowData['materName'],
									materType:rowData['materType'],
									materLevel:rowData['materLevel'],
									supId:rowData['supId'],
									supName:rowData['supName'],
									materValue:rowData['materValue'],
									materValueUndressed:rowData['materValueUndressed'],
									materProportion:rowData['materProportion'],
									materNum:rowData['materNum'],
									unit:rowData['unit'],
									brands:rowData['brands'],
									specifications:rowData['specifications']

                                }); 
							}
							,onUncheck:function(rowIndex,rowData){
								delete selectMap[rowData['mid']];
								var deleteIndex = $('#listDisplay2').datagrid('getRowIndex', rowData['mid']);
								if(deleteIndex!=-1){
		                            $('#listDisplay2').datagrid('deleteRow',deleteIndex); 
								}
                            }
							,onCheckAll:function(rows){
								for(var i=0;i<rows.length;i++){
                                    var table2Index = $('#listDisplay2').datagrid('getRowIndex',rows[i]['mid']);
                                    if(table2Index == -1){
                                    	$('#listDisplay2').datagrid('appendRow',{
                                            mid:rows[i]['mid'],
                                            materId:rows[i]['materId'],
                                            materName:rows[i]['materName'],
                                            materType:rows[i]['materType'],
                                            materLevel:rows[i]['materLevel'],
                                            supId:rows[i]['supId'],
                                            supName:rows[i]['supName'],
                                            materValue:rows[i]['materValue'],
                                            materValueUndressed:rows[i]['materValueUndressed'],
                                            materProportion:rows[i]['materProportion'],
                                            materNum:rows[i]['materNum'],
                                            unit:rowData['unit'],
                                            brands:rowData['brands'],
                                            specifications:rowData['specifications']
                                        }); 
                                    }
								    
								}
                            }
                            ,onUncheckAll:function(rows){
                                for(var i=0;i<rows.length;i++){
                                    var deleteIndex = $('#listDisplay2').datagrid('getRowIndex', rows[i]['mid']);
                                    $('#listDisplay2').datagrid('deleteRow',deleteIndex);
                                }
                            }
						
						});
				
			};
			
			function initList2(listDisplayEId) {
                $('#' + listDisplayEId).datagrid(
                        {
                            nowrap : false,
                            striped : true,
                            collapsible : true,
                            remoteSort : true,
                            notSelectByRow : false,
                            onCheck:function(rowIndex,rowData){
                            }
                        });
                
            };
			$(document).ready(function() {
		        getParentDocument();//获得父页面元素
                initList2('listDisplay2');
                initList('listDisplay');
			});
			function getParentDocument(){
				if(window.opener){
				    document.getElementsByName("ordId")[0].value =window.opener.document.getElementsByName("ordIdForDeal")[0].value;
		            document.getElementsByName("ordMaterId")[0].value =window.opener.document.getElementsByName("ordMaterId")[0].value;
                    document.getElementsByName("unusualDeal")[0].value =window.opener.document.getElementsByName("unusualDeal")[0].value;
                    document.getElementsByName("unusualDealDetailed")[0].value =window.opener.document.getElementsByName("unusualDealDetailed")[0].value;
                    document.getElementsByName("orderDate")[0].value =window.opener.document.getElementsByName("ordDate")[0].value;
		            document.getElementsByName("supId")[0].value =window.opener.document.getElementsByName("ordSupId")[0].value;
		            window.opener.close();
				}
			}
			
 			function addMater(){
 	 			$('#AddMaterForm').form('submit',
 				{
 					url:'<c:url value='/order/commitMaterOrderCon.do'/>', //查询提交路径
 					onSubmit:function()//提交按钮相应函数
 					{
 						return $('#AddMaterForm').form('validate');
 					},
 					success:function(data){
 						data = eval( "("+data+")" );
 		       			if(data.success){
 		       		        $.messager.alert('提示', '提交成功', 'info', function(){
                                window.close();
                            });
 	       				}else{
 	                        var message = "";
 	                        if(data.msg == "msg002"){
 	                            message = "所选择日期的材料订单已经下单完成，如需重新选择请删除已有订单。";
 	                        }else if(data.msg == "msg001"){
                                message = "选择材料的时间已过，请联系采购部。";
                            }
 	                        $.messager.alert("提示", message, 'warning');
 	                    }
 					},
 					error:function(){
 						$.messager.alert("错误", "系统错误，请联系管理员！", 'error');
 						return;
 					}
 				});
 	 			
 			}
 			//下拉框
			$(function() {        
		        $('#materType').combobox({   
                    url:"<c:url value='/mater/pulldownMaterType.do?space=1'/>",   
                    editable:true, //不可编辑状态  
                    cache: false,  
                    panelHeight: '150',  
                    valueField:'materType',     
                    textField:'materTypename',                      
                    }
		        );
		        $('#unusualDeal').combobox({   
                    url:"<c:url value='/unusual/pulldownUnusualDeal.do?space=0'/>",   
                    editable:true, //不可编辑状态  
                    cache: false,  
                    panelHeight: '150',  
                    valueField:'unusualDeal',     
                    textField:'unusualDealName',                      
                    }
		        ); 
		    });
			
		    function formatOptionField(val,rowData,rowIndex){
		    	var a= rowData['mid']+'';
                return "<a href='###' onclick='editrow("+a+")'><img src='../../images/cancel.png'/></a>";
            }         
		    function editrow(mid){
		    	//删除map对象中的复选框
		    	delete selectMap[mid];
		    	//删除已选列表中的行
                var index =  $('#listDisplay2').datagrid('getRowIndex', mid);
                $('#listDisplay2').datagrid('deleteRow', index)
                //取消勾选
                var indexlistDisplay =  $('#listDisplay').datagrid('getRowIndex', mid);
                if(indexlistDisplay != -1){
                    $('#listDisplay').datagrid("uncheckRow",indexlistDisplay);
                }
            }
		    
		    //订单状态格式
		    function formateSuperSelf(value, row, index, field) {
		        return "自采";
		    }
		</script>
			</head>
			<body>
			<form id="excelForm" name="excelForm" method="post"  enctype="multipart/form-data"
                        action="userlist.txt"
                        onsubmit="return searchDGData(this.id,'listDisplay');">
            </form>
			<form id="AddMaterForm" name="AddMaterForm" method="post" enctype="multipart/form-data">
			<table width="98%">
			<tr><td>
			<div style="height: auto; width:1180px;background: #fafafa; padding: 2px;" class="easyui-panel" title="&nbsp&nbsp&nbsp&nbsp&nbsp异常信息"  collapsible="true" minimizable="false" maximizable="false" closable="false">
			   <table cellpadding="5">
			      <tr>
                  	<td>关联订单id</td>
                    <td>
 			            <input class="easyui-validatebox" name="ordId" id="ordId"  data-options="required:true"  readonly="readonly"/> 
 			        </td>
 			        <td>异常材料id</td>
                    <td>
                        <input class="easyui-validatebox" name="ordMaterId" id="ordMaterId"  data-options="required:true" readonly="readonly"/> 
                    </td>
                    <td>处理方式</td>
                    <td>
                        <input class="easyui-validatebox" name="unusualDeal" id="unusualDeal"  data-options="required:true" readonly="readonly"/> 
                    </td>
                    <td>材料使用日期</td>
                    <td>
                        <input class="easyui-validatebox" name="orderDate" id="orderDate" editable="false" data-options="required:true"  readonly="readonly"/> 
                    </td>
                    
                  </tr>
                  <tr>
                    <td>处理明细内容</td>
                    <td>
                        <input class="easyui-validatebox" name="unusualDealDetailed" id="unusualDealDetailed"  data-options="required:true" readonly="readonly"/> 
                    </td>
                    <td>
				        <input class="easyui-validatebox" type="hidden" name="materdategridList"  />
 			        </td>
 			         <td>
                        <input class="easyui-validatebox" type="hidden" name="supId"  />
                    </td>
                  </tr>
               </table>
             </div>
           </td></tr>
           </table>
		<table width="98%">
		<tr style="height: 12px;"></tr>
		<tr>
		<td>
				<table id="listDisplay" title="选取材料列表" 
			iconCls="icon-list" singleSelect="false" idField="mid"
			loadMsg="请稍候......"
			pagination="true" pageSize="10"
			pageList="[10,20,30,40,50,100]" sortName="mid"
			rownumbers="true" sortOrder="asc">
			<thead>
				<tr>
				    <th field="materRole" width="25" align="center"  checkbox="true">
					</th> 
					<th field="mid" width="80" sortable="true" hidden="true">ID
					</th>
				    <th field="materId" width="50" sortable="true"  >材料ID
					</th>	
 					<th field="materName" width="140"  sortable="true">材料名
					</th>		
					<th field="materType" width="60" formatter="formatFoodType1" sortable="true" >种类
					</th>	
					<th field="unit" width="60"  sortable="true" >单位
                    </th>
                    <th field="brands" width="60" sortable="true" >品牌
                    </th>
                    <th field="specifications" width="60" sortable="true" >规格
                    </th>
					<th field="materLevel" width="50" formatter="formatFoodType" sortable="true"  hidden="true">品级
					</th>	
					<th field="supId" width="80" sortable="true" hidden="true" >供货商ID
					</th>
					<th field="supName" width="80" sortable="true">供货商名
					</th>
					<th field="materValue" width="120"  sortable="true" align="right" hidden="true">净料价格 （每公斤）
					</th>	
					<th field="materValueUndressed" width="120"  sortable="true" align="right" >毛料价格 （每公斤）
					</th>	
					<th field="materProportion" width="100"  sortable="true" align="right">毛料率（%）
					</th>
					<th field="materNum" width="150" sortable="true" editor="text" align="center"  >重量（毛料公斤）/个/份
					</th>	
 				</tr>
			</thead>
			</table>
			</td>
			</tr>
			<tr style="height: 12px;"></tr>
        <tr>
        <td>
                <table id="listDisplay2" title="已选材料列表" 
            iconCls="icon-list" singleSelect="false" idField="mid"
            loadMsg="请稍候......"
            pagination="false" sortName="mid"
            rownumbers="true" sortOrder="asc">
            <thead>
                <tr>
                    <th field="materRole" width="25" align="center"  checkbox="false">
                    </th> 
                    <th field="mid" width="80" sortable="true" hidden="true">
                        ID
                    </th>
                    <th field="materId" width="50" sortable="true" >材料ID
                    </th>   
                    <th field="materName" width="140"  sortable="true"  >材料名
                    </th>       
                    <th field="materType" width="60" formatter="formatFoodType1" sortable="true" >种类
                    </th>   
                    <th field="unit" width="60"  sortable="true" >单位
                    </th>
                    <th field="brands" width="60" sortable="true" >品牌
                    </th>
                    <th field="specifications" width="60" sortable="true" >规格
                    </th>
                    <th field="materLevel" width="50" formatter="formatFoodType" sortable="true" hidden="true" >品级
                    </th>   
                    <th field="supId" width="80" sortable="true" hidden="true" >供货商ID
                    </th>
                    <th field="supName" width="80" sortable="true" formatter="formateSuperSelf" >供货商名
                    </th>
                    <th field="materValue" width="120"  sortable="true" align="right" >净料价格 （每公斤）
                    </th>   
                    <th field="materValueUndressed" width="120"  sortable="true" align="right">毛料价格 （每公斤）
                    </th>   
                    <th field="materProportion" width="100"  sortable="true" align="right" >毛料率（%）
                    </th>
                    <th field="materNum" width="150" sortable="true" editor="text" align="center"  >重量（毛料公斤）/个/份
                    </th>
                    <th field="button" width="40" align="center" formatter="formatOptionField">删除</th>
                </tr>
            </thead>
            </table>
            </td>
            </tr>
		</table>
		</form>
	</body>
</html>
